


var AjaxUrls = {
	list : "http://yd.12301.cc/testshoppingcart.php",
	save : "",
	remove : "http://yd.12301.cc/shoppingcartdelete.php"
};

function hotelCheckTime(type,begintime,endtime){
	if(type !== "C") return { begin:begintime,end:endtime};
	var today = Calendar.gettoday();
	var nextday = Calendar.nextday();
	//var todaytime = new Date(today).getDate().toString();
	//var nexttime = new Date(nextday).getDate().toString();
	//var _begintime = new Date(begintime).getDate().toString();
	//var _endtime = new Date(endtime).getDate().toString();
	if(begintime == today) return { begin:begintime,end:endtime};
	
	if(G.btime(begintime,today)){ //如果开始时间小于今天
		begintime = today;
	}
	if(G.btime(endtime,nextday)){ //如果结束时间小于明天
		endtime = nextday;
	}

	return { begin:begintime,end:endtime }
	
}

(function(){
	
	var UI = {
		init : function(){
			this.bindEvent();
			this.calendarInit();
			
		},
		bindEvent : function(){
			var that = this;
			$("#mainCart").on("change",".countInp",function(e){
				var inp = $(e.target);
				var parent = inp.parents(".uu");
				if(!G.isPositiveNum(inp.val()) && (inp.val()!="0")){
					alert("输入的值必须为正整数");
					inp.val(1);
					countTotal();
					return false;
				}
				var val = parseInt(inp.val());
				var result = that.isAllowChangeCount(inp,val,"change");
				var storage = parseInt(inp.prev().val());
				if(result.isAllow){
					inp.val(val);
				}else{
					alert(result.mesg);
					inp.val(storage);
				}
				var price = parent.find(".col_3 .num").text();
				var newCount = inp.val();
				price = parseFloat(price);
				newCount = parseInt(newCount);
				parent.find(".stolW .num").text(G._round2(price*newCount,2));
				countTotal();
				return false;
			}).on("click",".countW .btns",function(e){
				var target = $(e.target);
				var inp = target.siblings(".countInp");
				var parent = inp.parents(".uu");
				var item = parent.parents(".cartItem");
				if(item.hasClass("unselect")){
					return false;
				}
				var val = parseInt(inp.val());
				var newVal = target.hasClass("minuBtn") ? val-1 : val+1;
				var result = that.isAllowChangeCount(target,newVal);
				if(result.isAllow){
					inp.val(newVal);
					var price = parent.find(".col_3 .num").text();
					var newCount = inp.val();
					price = parseFloat(price);
					newCount = parseInt(newCount);
					parent.find(".stolW .num").text(G._round2(price*newCount,2));
					countTotal();
				}else{
					alert(result.mesg)
				}
			}).on("click","input.pcheckbox",function(e){
				var target = $(e.target);
				var parent = target.parents(".cartItem");
				var checkboxAll = $("input.selectAll");
				var isAllSelect = that.isAllSelect();
				if(target.attr("checked")){
					if(isAllSelect){
						checkboxAll.attr("checked",true);
					}else{
						checkboxAll.attr("checked",false);
					}
					parent.find("ul.uu input").removeAttr("disabled");
					parent.find("input.countInp").attr("readOnly",false)
					parent.removeClass("unselect");
				}else{ //取消勾选
					parent.find("ul.uu input").attr('disabled',"true");
					parent.addClass("unselect");
					parent.find("input.countInp").attr("readOnly",true)
					checkboxAll.attr("checked",false);
				}
				countTotal();
			}).on("click","ul.uu .removeBtn",function(e){ //删除某个
				var target = $(e.currentTarget);
				var parent = target.parents(".uu");
				var tid = parent.find("input.uuqtid").val();
				var arrUls = [];
				arrUls.push(parent);
				removeSave(tid,arrUls);
				return false;
			})
			$("#removeAllB").on("click",function(e){ //删除选中的所有
				var tids = [];
				var uls = [];
				var lisSelected = $("#mainCart > .cartItem").filter(function(){
					return !$(this).hasClass("unselect");
				});
				lisSelected.each(function(index,li){
					var uus = $(li).find("ul.uu");
					uus.each(function(i,uu){
						tids.push($(uu).find("input.uuqtid").val());
						uls.push($(uu));
					})
				})
				tids = tids.join(",");
				if(!tids) return false;
				removeSave(tids,uls)
				return false;
			})
			$("#wrapCon input.selectAll").on("click",function(e){
				that.allSelectCancel($(e.target));
			})
			$("#submitBtn").click(function(e){
				if($(this).hasClass("disable")){
					return false;
				}
			})
		},
		isAllowChangeCount : function(targetInp,newVal,type){
			var target = targetInp;
			var inp = target.siblings(".countInp");
			var storage = type == "change" ? parseInt(target.prev().val()) : parseInt(inp.prev().val());
			if(newVal>storage){
				return { isAllow:false, mesg:"不能超过该商品当前库存量"+storage }
			}else if(newVal<0){
				return { isAllow:false, mesg:"数量不能为负数" }
			}else{
				return { isAllow:true }
			}
		},
		allSelectCancel : function(targetCheckbox){
			if(targetCheckbox.attr("checked")){
				$("#mainCart").find(".cartItem .checkboxW .pcheckbox").attr("checked",true);
				$(".selectAll").attr("checked",true);
				$("#mainCart").find("input.countInp").attr("readOnly",false)
				$("#mainCart > .cartItem").removeClass("unselect");
				$("#mainCart").find(".cartItem ul.uu input").removeAttr("disabled");
			}else{
				$("#mainCart").find(".cartItem .checkboxW .pcheckbox").attr("checked",false);
				$(".selectAll").attr("checked",false);
				$("#mainCart").find("input.countInp").attr("readOnly",true)
				$("#mainCart > .cartItem").addClass("unselect");
				$("#mainCart").find(".cartItem ul.uu input").attr('disabled',"true");
			}
			countTotal();
		},
		isAllSelect : function(){
			var result = true;
			$("#mainCart").find(".cartItem .checkboxW .pcheckbox").each(function(index,checkbox){
				if(!$(checkbox).attr("checked")){
					result = false;
					return;
				}
			})
			return result;
		},
		calendarInit : function(){
			Calendar.init.handles.push(function(elem){
				elem = $(elem);
				var date = elem.attr("date");
				var tarInp = $(Calendar.init.timeElement);
				var p = tarInp.parents("ul.uu");
				var pid = p.find("input.tid").val();
				$.ajax({
					"url":"../call/ajax_price_u.php",
					"data":{"date":date,"pid":pid},
					"async":false,
					"dataType":"json",
					"success":function(data){
						for(var pid in data){
							var jsprice_str="tprice_"+pid;
							var uprice_str="uprice_"+pid;
							var storage_str="storage_"+pid;
							if($("input[type='hidden']."+jsprice_str).size()>0){
								if(data[pid]['jsprice']>=0){
									$("input[type='hidden']."+jsprice_str).val(data[pid]['jsprice']/100);
									$("em."+jsprice_str).html("¥"+data[pid]['jsprice']/100);
									$("em."+uprice_str).html("¥"+data[pid]['uprice']/100);
									$("em."+storage_str).html(data[pid]['storage']);
								}else{
									var con=$("input[type='hidden']."+jsprice_str).get(0);
									con.parentNode.parentNode.parentNode.removeChild(con.parentNode.parentNode);
								}
							}
						}
						countTotal();
					}
				})
			});
			Calendar.init.handles.push(function(elem){
				elem = $(elem);
				var price = elem.attr("data-price");
				var targetInp = $(Calendar.init.timeElement);
				var uu = targetInp.parents("ul.uu");
				var btime = uu.find(".timeW input.begin").val();
				var etime = uu.find(".timeW input.end").val();
				var count = uu.find(".countW input.countInp").val();
				if(btime && etime){
					if(btime == etime || !G.btime(btime,etime)){ //如果开始时间>结束时间
						alert("入住时间必须早于离店时间(入住时间至少为1天)");
						targetInp.val(Calendar.init.odate);
						return false;
					}
				}
				//计算天数
				var idate = G.DateDiff(btime,etime);
				idate = idate ? idate : 1; //天数至少为一天
				price = G._round2(price*idate,2);
				uu.find("li.col_3 .num").text(price);
				uu.find("li.stolW .num").text(G._round2(price*count,2));
				
				countTotal();
			})
			Calendar.init.handles.push(function(elem){
				elem = $(elem);
				var price = elem.find(".price").text();
				price = price.substring(1);
				//Calendar.init.timeElement.val(price)
			});
			$("#mainCart").on("click",".timeInpW .timeInp",function(e){
				Calendar.init.timeElement=this;
				var target = $(e.target);
				var tval = target.val();
				Calendar.init.odate = tval;
				var p = $(target.parents("ul.uu"));
				var pid = p.find("input.tid").val();
				var date=$(this).val(),
					yearmonth=date.substr(0,7),
					aid=parseInt(p.find("input.aid").val());
				$(this).blur();
				Calendar.show(yearmonth,pid,0,2);
			});
		}
	};
	
	
	function getList(){
		getList.status.loading();
		$.ajax({
			url : G_CONFIG.url.getCartList,
			type : "GET",
			dataType : "JSON",
			success : function(res){
				if(res && res.code && res.list){
					if(!G.isEmpty(res.list)){
						getList.status.success();
						buildList(res.list)
					}else{
						getList.status.empty();
					}
				}else{
					getList.status.bus();
				}
			},
			error : function(xhr,text){
				if(text == "timeout"){
					getList.status.error("timeout");
				}else{
					getList.status.error("bus");
				}
			}
		})
	}
	getList.status = { 
		loading : function(){ //loading 
			var loading = '<li class="loading" style="text-align:center; line-height:1; height:400px;"><p style="color:#aeaeae; font-size:12px; padding-top:150px;">加截数据...</p><img src="http://www.12301.cc/yd/images/loading_1.gif" alt="" /></li>';
			$("#mainCart").html(loading);
			$("#botSumary").hide();
		},
		empty : function(){ //空数据
			var html = '<li style="height:400px; line-height:400px; text-align:center; color:#b4b4b4;" class="removeToEmpty">没有商品，去<a style="margin:0 3px; font-weight:bold; color:#3375b8" href="./gtindex.html">首页</a>逛逛</li>';
			$("#mainCart").html(html);
			$("#botSumary").hide();
		},
		success : function(){ //成功请求
			$("#botSumary").show();
		},
		error : function(type){
			//type : timeout //超时
			//type : server  //服务器端出错
			//type : bus     //业务逻辑出错
			var timeout = '<li style="height:400px; line-height:400px; text-align:center; color:#b4b4b4;" class="removeToEmpty">请求超时，请稍后刷新重试</li>';
			var server = '<li style="height:400px; line-height:400px; text-align:center; color:#b4b4b4;" class="removeToEmpty">服务器出错 / 帐号登录过期，请重新登录</li>';
			var bus = '<li style="height:400px; line-height:400px; text-align:center; color:#b4b4b4;" class="removeToEmpty">请求出错，请稍后刷新重试</li>';
			if(type == "timeout"){
				$("#mainCart").html(timeout);
			}else if(type == "server"){
				$("#mainCart").html(server);
			}else if(type == "bus"){
				$("#mainCart").html(bus);
			}
			$("#botSumary").hide();
		}
	};
	
	function removeSave(tids,arrUls){
		removeSave.status.loading(arrUls);
		$.ajax({
			url : G_CONFIG.url.cartRemoveItem,
			type : "POST",
			dataType : "JSON",
			data : {
				tids : tids
			},
			success : function(res){
				if(res && res.code == 200){
					$.each(arrUls,function(index,ul){
						//ul = $(ul);
						var cartItem = ul.parents(".cartItem");
						var siblings = ul.siblings();
						ul.remove();
						if(!siblings.length){
							cartItem.remove();
						}
					})
					if(!$("#mainCart").find("li.cartItem").length){
						$("#mainCart").html('<li style="height:400px; line-height:400px; text-align:center; color:#b4b4b4;" class="removeToEmpty">没有商品，去<a style="margin:0 3px; font-weight:bold; color:#3375b8" href="'+G_CONFIG.url.jumpToIndex+'">首页</a>逛逛</li>');
						$("#botSumary").hide();
					}
					countTotal();
				}else if(res && res.code == 104){
					alert("未登录，请登录后重试")
				}else{
					removeSave.status.error(uls);
				}
			},
			error : function(xhr,text){
				if(text == "timeout"){
					removeSave.status.timeout(uls);
				}else{
					removeSave.status.error(uls);
				}
			}
		})
	}
	removeSave.status = {
		loading : function(arruls){ 
			$.each(arruls,function(index,uls){
				uls.each(function(index,ul){
					ul = $(ul);
					ul.find("a.removeBtn").text("删除")
				})
			})
		},
		success : function(uls){},
		timeout : function(uls){ 
			$.each(arruls,function(index,uls){
				uls.each(function(index,ul){
					ul = $(ul);
					ul.find("a.removeBtn").text("删除")
				})
			})
			alert("请求超时，请稍后重试");
		},
		error : function(uls){ 
			$.each(arruls,function(index,uls){
				uls.each(function(index,ul){
					ul = $(ul);
					ul.find("a.removeBtn").text("删除")
				})
			})
			alert("请求超时，请稍后重试");
		}
	}
	
	function buildList(datas){
		var html = "";
		var isSelected = "false";
		var cls = "";
		var readOnly = "";
		for(var i in datas){
			var data = datas[i];
			var type = data["type"];
			var lid = i;
			var landtit = data["title"];
			var subs = data["subs"];
			var isSelected = data.isSelected == 1 ? "checked='checked'" : "";
			var readOnly = data.isSelected == 1 ? "" : "readOnly='true'";
			var cls = data.isSelected == 1 ? "" : "unselect";
			if(type == "G"){ //餐饮类
				for(var s in subs){
					var sub = subs[s];
					var tid = s;
					var pid = sub["pid"];
					var aid = data["aid"];
					var ttitle = sub["title"];
					var tdate = sub["date"];
					var tprice = sub["price"];
					var tcount = sub["count"];
					var tstorage = sub["storage"];
					var stoal = G._round2(tprice*tcount,2);
					html += '<li id="eat'+lid+'_'+tid+'" class="cartItem '+type+' '+cls+'">';
					html += 	'<input type="hidden" name=lid['+pid+'_'+tid+'] class="lid" value="'+lid+'"/>';
					html += 	'<input type="hidden" class="ptype" name="ptype['+pid+'_'+tid+']" value="'+type+'"/>';
					html += 	'<p class="topTit"><span class="checkboxW"><input type="checkbox" '+isSelected+' name="" id="" class="pcheckbox"/></span><span class="t">'+landtit+'</span></p>';;
					html += 	'<div class="con">';
					html +=			'<ul id="eatp'+tid+'" class="uu clearfix">';
					html +=         	'<input type="hidden" name="pid['+pid+'_'+tid+']" class="tid" value="'+pid+'"/>';
					html +=         	'<input type="hidden" class="uuqtid" value="'+tid+'"/>';
					html +=         	'<input type="hidden" class="uuqaid" name="aid['+pid+']" value="'+aid+'"/>';
					html +=     		'<li class="dli col col_1">'+ttitle+'</li>';
					html += 			'<li class="dli col col_2 timeW">';
					html +=					'<input type="hidden" class="storage" value="'+tstorage+'"/>'
					html += 				'<span class="timeInpW single"><input type="text" name="begintime['+pid+'_'+tid+']" id="" class="timeInp" value="'+tdate+'" '+readOnly+'/><i class="icon"></i></span>'
					html +=				'</li>';
					html +=				'<li class="dli col col_3"><span class="yen">&yen;</span><span class="num">'+tprice+'</span></li>';
					html +=				'<li class="dli col col_4 countW"><div class="cc"><input type="hidden" class="storage" value="'+tstorage+'"/><input type="text" name="tnum['+pid+'_'+tid+']" id="" value="'+tcount+'" class="countInp" '+readOnly+'/><span class="btns minuBtn">-</span><span class="btns addBtn">+</span></div></li>';
					html += 			'<li class="dli col col_5 stolW"><span class="yen">&yen;</span><span class="num">'+stoal+'</span></li>';
					html +=				'<li class="dli col col_6"><input type="hidden" name="" value="'+tid+'"/><a class="removeBtn" href="#">删除</a></li>';
					html +=			'</ul>';
					html += 	'</div>';
					html += '</li>';
				}
			}else{
				html += '<li id="cartItem'+lid+'" class="cartItem '+type+' '+cls+'">';
				html += 	'<p class="topTit"><span class="checkboxW"><input type="checkbox" '+isSelected+' name="" id="" class="pcheckbox"/></span><span class="t">'+landtit+'</span></p>';;
				html += 	'<div class="con">';
								for(var a in subs){
									var sub = subs[a];
									var tid = a;
									var pid = sub["pid"];
									var aid = data["aid"];
									var ttitle = sub["title"];
									var tdate = sub["date"];
									var begintime = tdate["begin"];
									var endtime = tdate["end"];
									var tprice = sub["price"];
									var tcount = sub["count"];
									var tstorage = sub["storage"];
									var stoal = G._round2(tprice*tcount,2);
									html +=			'<ul id="eatp'+tid+'" class="uu clearfix">';
									html +=         	'<input type="hidden" name="pid['+pid+']" class="tid" value="'+pid+'"/>';
									html += 			'<input type="hidden" name=lid['+pid+'] class="lid" value="'+lid+'"/>';
									html += 			'<input type="hidden" class="ptype" name="ptype['+pid+']" value="'+type+'"/>';
									html +=         	'<input type="hidden" class="uuqtid" value="'+tid+'"/>';
									html +=         	'<input type="hidden" class="uuqaid" name="aid['+pid+']" value="'+aid+'"/>';
									html +=     		'<li class="dli col col_1">'+ttitle+'</li>';
									html += 			'<li class="dli col col_2 timeW">';
															if(sub.date.begin){
																endtime = hotelCheckTime(type,begintime,endtime).end;
																begintime = hotelCheckTime(type,begintime,endtime).begin;
																html += '<span class="timeInpW"><input type="text" name="endtime['+pid+']" id="" class="timeInp end" value="'+endtime+'" '+readOnly+'/><i class="icon"></i></span>';
																html +=	'<span class="t" style="display:block; position:relative; top:2px; width:20px; float:right; text-align:center;">至</span>';
																html += '<span class="timeInpW"><input type="text" name="begintime['+pid+']" id="" class="timeInp begin" value="'+begintime+'" '+readOnly+'/><i class="icon"></i></span>';
															}else{
																html += '<span class="timeInpW single"><input type="text" name="begintime['+pid+']" id="" class="timeInp" value="'+tdate+'" '+readOnly+'/><i class="icon"></i></span>';
															}
									html +=				'</li>';
									html +=				'<li class="dli col col_3"><span class="yen">&yen;</span><span class="num">'+tprice+'</span></li>';
									html +=				'<li class="dli col col_4 countW"><div class="cc"><input type="hidden" class="storage" value="'+tstorage+'"/><input type="text" name="tnum['+pid+']" id="" value="'+tcount+'" class="countInp" '+readOnly+'/><span class="btns minuBtn">-</span><span class="btns addBtn">+</span></div></li>';
									html += 			'<li class="dli col col_5 stolW"><span class="yen">&yen;</span><span class="num">'+stoal+'</span></li>';
									html +=				'<li class="dli col col_6"><input type="hidden" name="" value="'+tid+'"/><a class="removeBtn" href="#">删除</a></li>';
									html +=			'</ul>';
								}
				html += 	'</div>';
				html += '</li>';
			}
		}
		$("#mainCart").html(html);
		countTotal();
	}
	function countTotal(){
		var totalPrice = 0;
		var totalCount = 0;
		var isAllSelect = true;
		$("#mainCart").find("li.cartItem .checkboxW input.pcheckbox").each(function(index,input){
			input = $(input);
			if(input.attr("checked")){
				var pitem = input.parents(".cartItem");
				var count = pitem.find(".countW input.countInp").val();
				pitem.find("ul.uu").each(function(i,uu){
					var price = $(uu).find(".stolW .num").text();
					var num = $(uu).find(".countW .countInp").val();
					totalPrice += G._round2(price,2);
					if(num && Number(num)>0){
						totalCount++;
					}
				})
			}else{
				isAllSelect = false;
			}
			if(isAllSelect && $("#mainCart > li.cartItem").length){
				$("input.selectAll").attr("checked","checked")
			}else{
				$("input.selectAll").attr("checked",false)
			}
		});
		totalPrice = G._round2(totalPrice,2);
		//console.log("totalPrice="+totalPrice+"  totalCount="+totalCount)
		$("#topSumary").find("span.totalNum").text(totalCount);
		$("#topSumary").find("span.totalMoney").text(totalPrice);
		$("#botSumary").find("span.totalNum").text(totalCount);
		$("#botSumary").find("span.totalMoney").text(totalPrice);
		if(totalPrice == 0){
			$("#submitBtn").addClass("disable");
		}else{
			$("#submitBtn").removeClass("disable");
		}
	}
	
	
	$(function(){
		G.Login.init();
		G.checkLogin({
			logined : function(){
				getList();
				UI.init();
			},
			unlogin : function(){
				G.Login.open();
				$("#mainCart").html('<li style="text-align:center; line-height:1; height:400px;" class="loading"><p style="color:#aeaeae; font-size:12px; padding-top:150px;">未登录 / 帐号登录已过期</p></li>')
			}
		})
		
		
	})
	
	
	
})();


